/**
 * 
 */
package org.t2.game.server.module.recharge.service;

import org.gaming.service.service.AbstractService;
import org.gaming.tool.DateTimeUtil;
import org.gaming.tool.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.t2.design.module.RechargeTable;
import org.t2.design.module.autogen.RechargeAbstractTable.RechargeCfg;
import org.t2.game.server.foundation.starting.ApplicationSettings;
import org.t2.game.server.module.player.model.Player;
import org.t2.game.server.module.player.service.PlayerService;
import org.t2.game.server.module.recharge.model.RechargeOrder;
import org.t2.game.server.module.tips.GameCause;

import sh.t2.share.module.recharge.RechargeExtra;

/**
 * 
 */
@Service
public class RechargeOrderService extends AbstractService<RechargeOrder> {

	@Autowired
	private PlayerService playerService;
	@Autowired
	private ApplicationSettings applicationSettings;
	
	
	public RechargeOrder getEntity(String id) {
		return this.repository().getByKeys(id);
	}
	
	@Override
	public void mergeServer(int mergeDbZoneId) {
		// TODO Auto-generated method stub
		
	}
	
	public void checkOrdering(long playerId, int productId) {
		//有待实现
	}
	
	/**
	 * 
	 * @param playerId
	 * @param productId
	 * @param productData
	 * @param virtual 是否虚拟订单（GM订单）
	 * @return
	 */
	public RechargeOrder createOrder(long playerId, int productId, boolean virtual, GameCause gameCause) {
		Player player = playerService.getEntity(playerId);
		
		RechargeCfg rechargeCfg = RechargeTable.ins().getInIdIndex(productId);
		
		RechargeOrder recharge = null;
		while(true) {
			try {
				String timeStamp = DateTimeUtil.formatMillis(DateTimeUtil.YYYYMMDDHHMMSSSSS, DateTimeUtil.currMillis());
				int randomNum = RandomUtil.closeClose(10000, 99999);
				
				recharge = new RechargeOrder();
				recharge.setId("R" + timeStamp + "" + randomNum);
				recharge.setPlayerId(player.getId());
				recharge.setNick(player.getNick());
				recharge.setServerId(player.getServerId());
				recharge.setProductId(rechargeCfg.getId());
				recharge.setProductName(rechargeCfg.getName());
				recharge.setPrePayMoney(rechargeCfg.getPrice());
				recharge.setVirtual(virtual);
				recharge.setGameCause(gameCause.getCode());
				recharge.setGameCauseText(gameCause.getDesc());
				this.insert(recharge);
				break;
			} catch (Exception e) {
				//ID重复异常
			}
		}
		
		RechargeExtra rechargeExtra = new RechargeExtra();
		rechargeExtra.setOrderId(recharge.getId());
		rechargeExtra.setProductId(recharge.getProductId());
		rechargeExtra.setPlayerId(recharge.getPlayerId());
		rechargeExtra.setMoney(recharge.getPrePayMoney());
		rechargeExtra.setOpenId(player.getOpenId());
		rechargeExtra.setSign(rechargeExtra.buildSign(applicationSettings.getBackstageKey()));
		
        recharge.setExtraInfo(rechargeExtra.encode());
        this.update(recharge);
        return recharge;
	}
}
